package com.ruoyi.system.controller.mine;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.domain.Emplyee;
import com.ruoyi.system.dto.SalaryDto;
import com.ruoyi.system.service.IEmplyeeService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.vo.SalaryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.Salary;
import com.ruoyi.system.service.ISalaryService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 工资 Controller
 *
 * @author ruoyi
 * @date 2023-10-13
 */
@RestController
@RequestMapping("/salary")
public class SalaryController extends BaseController
{
    @Autowired
    private ISalaryService salaryService;
    @Autowired
    private IEmplyeeService emplyeeService;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询salary列表
     */
    @RequiresPermissions("mine:salary:list")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody SalaryDto dto) throws ParseException {
        System.out.println("工资dto："+dto);
        //根据姓名查询eno
        Emplyee emplyee = emplyeeService.selectEmplyeeByName(dto.getName());
        Salary salary = new Salary();
        if(emplyee!=null){
            salary.setEno(emplyee.getEno());
        }
        if(dto.getDateMonth()!=null){
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //将日期类型转为字符串
            String dateStr = format.format(dto.getDateMonth());
            //截取年月
            String dateRes = dateStr.substring(0,dateStr.lastIndexOf("-"));
            //将字符串类型转为日期
            DateFormat formatRes = new SimpleDateFormat("yyyy-MM");
            Date parseDate = formatRes.parse(dateRes);
            salary.setDateMonth(parseDate);
        }else{
            //默认查询年月
            String str = "2023-12";
            //将字符串类型转为日期
            DateFormat formatMo = new SimpleDateFormat("yyyy-MM");
            Date parse = formatMo.parse(str);
            salary.setDateMonth(parse);
        }
        startPage();
        List<Salary> list = salaryService.selectSalaryList(salary);
        List<SalaryVo> listRes = new ArrayList<>();
        //设置部门名称
        for (Salary sal : list) {
            SalaryVo salaryVo = new SalaryVo();
            SysDept sysDept = deptService.selectDeptById(sal.getDeptId());
            BeanUtils.copyProperties(sal,salaryVo);
            salaryVo.setDeptName(sysDept.getDeptName());
            listRes.add(salaryVo);
        }
        System.out.println("list"+listRes);
        return getDataTable(listRes);
    }

    /**
     * 导出salary列表
     */
    @RequiresPermissions("mine:salary:export")
    @Log(title = "salary", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Salary salary)
    {
        List<Salary> list = salaryService.selectSalaryList(salary);
        ExcelUtil<Salary> util = new ExcelUtil<Salary>(Salary.class);
        util.exportExcel(response, list, "salary数据");
    }

    /**
     * 获取salary详细信息
     */
    @RequiresPermissions("mine:salary:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(salaryService.selectSalaryById(id));
    }

    /**
     * 新增salary
     */
    @RequiresPermissions("mine:salary:add")
    @Log(title = "salary", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Salary salary)
    {
        return toAjax(salaryService.insertSalary(salary));
    }

    /**
     * 修改salary
     */
    @RequiresPermissions("mine:salary:edit")
    @Log(title = "salary", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Salary salary)
    {
        //根据事假天数计算事假扣款
        if (salary != null && salary.getAbsence() != null) {
            // 根据请假天数计算扣款，假设每天扣款150
            int absenceDays = salary.getAbsence();
            BigDecimal absenceFine = new BigDecimal(absenceDays * 150);
            System.out.println("最后计算的扣款："+absenceFine);
            // 设置计算得到的扣款金额
            salary.setAdsenceFine(absenceFine);
        }
        //根据加班时长计算加班工资
        if(salary!=null && salary.getOverwork()!=null){
            int overworkHours = salary.getOverwork();
            BigDecimal overworkWages = new BigDecimal(overworkHours * 20);
            System.out.println("最后计算的加班工资:"+overworkWages);
            // 设置计算得到的加班工资
            salary.setOverworkWages(overworkWages);

        }
        //计算实际工资
        BigDecimal realWages = salary.getBaseWages().add(salary.getBonus())
                .subtract(salary.getAdsenceFine())
                .add(salary.getOverworkWages())
                .subtract(salary.getSocial());
        salary.setRealWages(realWages);
        return toAjax(salaryService.updateSalary(salary));
    }

    /**
     * 删除salary
     */
    @RequiresPermissions("mine:salary:remove")
    @Log(title = "salary", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(salaryService.deleteSalaryByIds(ids));
    }
}
